<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="客户姓名" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入客户姓名" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户手机" prop="phone">
                <el-input v-model="queryParams.phone" placeholder="请输入客户手机号码" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="归属人" prop="owner">
                <el-input v-model="queryParams.owner" placeholder="请输入商机归属人" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="跟进时间">
                <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar :show-search="showSearch" @update:show-search="showSearch = $event"
                @queryTable="getData"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="客户姓名" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" prop="phone" :show-overflow-tooltip="true" />
            <el-table-column label="商机归属" prop="owner" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="商机状态" prop="status">
                <template #default="scope">
                    <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{ scope.row.status == 1 ? '已分配' : '未分配'
                    }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="下次跟进时间" prop="nextTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.nextTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
                    <el-button link type="primary" icon="Share" @click="handleAllocate(scope.row)">分配</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10]"
            :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        <!-- 添加对话框和编辑对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="businessRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select v-model="form.channelId" placeholder="渠道来源" clearable style="width: 100%"
                                @change="handleChannelChange">
                                <el-option v-for="dict in channelOptions" :key="dict.channelId"
                                    :label="dict.channelName" :value="dict.channelId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityId">
                            <el-select v-model="form.activityId" placeholder="活动信息" clearable style="width: 100%">
                                <el-option v-for="dict in activityOptions" :key="dict.value" :label="dict.name"
                                    :value="dict.activityId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户性别" prop="gender">
                            <el-radio-group v-model="form.gender">
                                <el-radio :label="0">男</el-radio>
                                <el-radio :label="1">女</el-radio>
                                <el-radio :label="2">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户年龄" prop="age">
                            <el-input-number v-model="form.age" :min="0" :max="200" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="微信号" prop="wechat">
                            <el-input v-model="form.wechat" placeholder="请输入微信号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ号码" prop="qq">
                            <el-input v-model="form.qq" placeholder="请输入QQ号码" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" v-if="title == '添加商机'">确 定</el-button>
                    <el-button type="primary" @click="edithanle" v-else>编 辑</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 分配对话框 -->
        <el-dialog :title="allocateTitle" v-model="allocateOpen" width="700px" append-to-body>
            <el-form ref="allocateRef" :model="allocateForm" :rules="allocateRules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="归属部门" prop="departmentId">
                            <el-tree-select v-model="allocateForm.departmentId" :data="deptOptions"
                                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                placeholder="请选择归属部门" check-strictly style="width: 100%" @change="handleDeptChange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分配给" prop="userId">
                            <el-select v-model="allocateForm.userId" placeholder="请选择分配人" clearable style="width: 100%">
                                <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName"
                                    :value="user.userId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitAllocateForm">确 定</el-button>
                    <el-button @click="cancelAllocate">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { getList, getqudao, gethuodong, addshangji, deletesj, editsj, editshangji, deptTreeSelect, fenpeigei, fenpei } from "../../../api/bus/busApi";
import { parseTime } from "@/utils/ruoyi";
import RightToolbar from "@/components/RightToolbar/index.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
const {proxy} = getCurrentInstance();
const list = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const dateRange = ref([]);

// Dialog related
const open = ref(false);
const title = ref("");
// 分页
const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    pageSize.value = val;
    getData();
}
const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    pageNum.value = val;
    getData();
}
const form = reactive({
    id: undefined,
    phone: undefined,
    name: undefined,
    channelId: undefined,
    activityId: undefined,
    gender: 0,
    age: 0,
    weixin: undefined,
    qq: undefined
});
const businessRef = ref(null); // Ref for the form

const rules = reactive({
    phone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "客户姓名不能为空", trigger: "blur" }],
});

// Dummy options for select, replace with actual data fetching later
//渠道来源
const channelOptions = ref([]);
const getqudaoData = async () => {
    const res = await getqudao();
    // console.log(res);
    if (res.code == 200) {
        channelOptions.value = res.data;
    }
}
getqudaoData();

//活动信息
const activityOptions = ref([]);
//渠道来源变化处理
async function handleChannelChange() {
    //    console.log("渠道来源变化", form.channelId);
    const res = await gethuodong(form.channelId);
    // console.log(res);
    if (res.code == 200) {
        activityOptions.value = res.data;
    }
}


const queryParams = reactive({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: undefined,
    phone: undefined,
    owner: undefined,
    beginTime: undefined,
    endTime: undefined
});

const queryRef = ref(null); // Ref for the form

const getData = async () => {
    loading.value = true;
    queryParams.pageNum = pageNum.value;
    queryParams.pageSize = pageSize.value;
    if (dateRange.value && dateRange.value.length === 2) {
        queryParams.beginTime = dateRange.value[0];
        queryParams.endTime = dateRange.value[1];
    } else {
        queryParams.beginTime = undefined;
        queryParams.endTime = undefined;
    }
    const res = await getList(queryParams);
    if (res.code == 200) {
        list.value = res.rows;
        total.value = res.total;
    }
    loading.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
    pageNum.value = 1;
    getData();
}

/** 重置按钮操作 */
function resetQuery() {
    dateRange.value = [];
    queryRef.value.resetFields(); // Reset form fields
    handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    // console.log(selection);
    ids.value = selection.map(item => item.businessId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    // console.log(ids.value);
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加商机";
}

/** 重置表单 */
function reset() {
    form.id = undefined;
    form.phone = undefined;
    form.name = undefined;
    form.channelId = undefined;
    form.activityId = undefined;
    form.gender = null;
    form.age = 0;
    form.weixin = undefined;
    form.qq = undefined;
    if (businessRef.value) {
        businessRef.value.resetFields();
    }
}

/** 新增确定按钮 */
function submitForm() {
    businessRef.value.validate(async (valid) => {
        if (valid) {
            const res = await addshangji(form);
            // console.log(res);
            if (res.code == 200) {
                ElMessage.success({
                    type: "success",
                    message: res.msg
                });
                getData();
            }
            open.value = false;
        }
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

/** 修改按钮操作 */
async function handleUpdate(row) {
    reset();
    const businessId = ids.value[0];
    const res = await editsj(businessId)
    // console.log(res);
    if (res.code == 200) {
        form.phone = res.data.phone;
        form.businessId = res.data.businessId;
        form.name = res.data.name;
        form.channelId = res.data.channelId;
        form.activityId = res.data.activityId;
        form.gender = res.data.gender;
        form.age = res.data.age;
        form.weixin = res.data.weixin;
        form.qq = res.data.qq;
        handleChannelChange();
    }
    title.value = "修改商机";
    open.value = true;
}
// 编辑按钮
const edithanle = async () => {
    const res = await editshangji(form);
    console.log(res);
    if (res.code == 200) {
        ElMessage.success({
            message: res.msg,
            type: "success",
        });
    }
    open.value = false;
    getData();
}

/** 删除按钮操作 */
function handleDelete(row) {
    console.log("删除操作传入的row: ", row);
    const businessIds = row.id || ids.value;
    ElMessageBox.confirm(
        '是否确认删除商机编号为"' + businessIds + '"的数据项？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await deletesj(businessIds);
            if (res.code === 200) {
                getData();
                ElMessage.success({
                    type: "success",
                    message: res.msg
                });
            }
        })
        .catch(() => {
            ElMessage.info("已取消删除");
        });
}

/** 导出按钮操作 */
function handleExport() {
    ElMessageBox.confirm('是否确认导出当前页面的商机数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 构建导出参数，确保字段名与后端接口一致
        const exportParams = {
            pageNum:pageNum.value,
            pageSize:pageSize.value,
        };
        // 使用download方法进行文件下载
        proxy.download("tienchin/course/export", exportParams, `course_${new Date().getTime()}.xlsx`);
        // // 准备导出数据
        // const exportData = list.value.map(item => ({
        //     '客户姓名': item.name,
        //     '手机号码': item.phone,
        //     '商机归属': item.owner,
        //     '商机来源': item.owner,
        //     '创建时间': parseTime(item.createTime)
        // }));

        // // 创建工作簿
        // const wb = XLSX.utils.book_new();
        // // 创建工作表
        // const ws = XLSX.utils.json_to_sheet(exportData);
        // // 设置列宽
        // const colWidths = [
        //     { wch: 15 }, // 客户姓名
        //     { wch: 15 }, // 手机号码
        //     { wch: 15 }, // 商机归属
        //     { wch: 15 }, // 商机来源
        //     { wch: 15 }, // 商机状态
        //     { wch: 15 }, // 商机类型
        //     { wch: 15 }, // 商机金额
        //     { wch: 20 }  // 创建时间
        // ];
        // ws['!cols'] = colWidths;

        // // 将工作表添加到工作簿
        // XLSX.utils.book_append_sheet(wb, ws, '商机列表');

        // // 生成文件名
        // const fileName = `商机列表_${new Date().getTime()}.xlsx`;

        // // 导出文件
        // XLSX.writeFile(wb, fileName);

        // ElMessage.success('导出成功');
    }).catch(() => { });
}

/** 查看按钮操作 */
function handleView(row) {
    console.log("查看操作", row);
}

// 分配相关
const allocateOpen = ref(false);
const allocateTitle = ref("");
const allocateForm = reactive({
    assignId: undefined,
    departmentId: undefined,
    userId: undefined,
});
const allocateRef = ref(null);
const deptOptions = ref([]); // 清空模拟数据，将通过API获取
const userOptions = ref([]); // 根据选择的部门动态加载用户
const allocateRules = reactive({
    departmentId: [{ required: true, message: "归属部门不能为空", trigger: "change" }],
    userId: [{ required: true, message: "分配人不能为空", trigger: "change" }],
});

// 查询部门下拉树结构
async function getDeptTreeselect() {
    const res = await deptTreeSelect();
    // console.log(res);
    if (res.code === 200) {
        // deptOptions.value = handleTree(res.data, "id", "parentId", "children");
        deptOptions.value = res.data;
    }
}

const handleDeptChange = async (value) => {
    // value will be the single selected ID from el-tree-select
    const selectedDeptId = value;
    // console.log("选中的部门ID：", selectedDeptId);
    const res = await fenpeigei(selectedDeptId);
    // console.log(res);
    if (res.code == 200) {
        userOptions.value = res.data;
    }
    allocateForm.userId = undefined; // 清空已选的分配人
};

/** 分配按钮操作 */
function handleAllocate(row) {
    // console.log("分配操作", row);
    allocateOpen.value = true;
    allocateTitle.value = "分配商机";
    allocateForm.assignId = row.businessId;
    allocateForm.departmentId = undefined; // Reset for new allocation
    allocateForm.userId = undefined; // Reset for new allocation
    if (allocateRef.value) {
        allocateRef.value.resetFields();
    }
}

/** 提交分配表单 */
function submitAllocateForm() {
    allocateRef.value.validate(async (valid) => {
        if (valid) {
            // console.log("提交分配表单", allocateForm);
            const selectedUser = userOptions.value.find(user => user.userId === allocateForm.userId);
            const nickName = selectedUser ? selectedUser.nickName : undefined;
            const userName = selectedUser ? selectedUser.userName : undefined;
            const payload = {
                assignId: allocateForm.assignId,
                departmentId: allocateForm.departmentId,
                deptId: allocateForm.departmentId,
                userId: allocateForm.userId,
                nickName: nickName,
                userName: userName,
                type: 1,
            };

            // console.log("最终提交的分配参数", payload);
            const res = await fenpei(payload);
            // console.log(res);
            if (res.code === 200) {
                ElMessage.success({
                    type: "success",
                    message: res.msg
                });
                allocateOpen.value = false;
                getData();
            } else {
                ElMessage.error({
                    type: "error",
                    message: res.msg || "分配失败，请重试！"
                });
            }
        }
    });
}

/** 取消分配 */
function cancelAllocate() {
    allocateOpen.value = false;
    if (allocateRef.value) {
        allocateRef.value.resetFields();
    }
}

onMounted(() => {
    getDeptTreeselect();
});

getData();
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}

.el-form-item {
    margin-right: 20px;
    margin-bottom: 15px; // Adjust margin for better spacing
}

.mb8 {
    margin-bottom: 8px;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
}
</style>